import React, { useState } from "react";
import axios from "axios";
import "./App.css";
import {
  Layout,
  Card,
  Input,
  Button,
  List,
  Typography,
  message,
  Alert,
  Row,
  Col,
  ConfigProvider,
  theme,
  Switch,
  Space,
} from "antd";
import {
  CheckOutlined,
  InfoOutlined,
  MoonOutlined,
  SunOutlined,
} from "@ant-design/icons";

const { Search } = Input;
const { Content, Header } = Layout;
const { Paragraph, Text } = Typography;

// 定义命名风格说明的数据类型
interface NamingStyle {
  type: string;
  desc: string;
  example: string;
}

// 定义转换后的变量名类型
interface ConvertedName {
  original: string;
  camelCase: string;
  PascalCase: string;
  snake_case: string;
  kebab_case: string;
  UPPER_CASE: string;
  UPPER_SNAKE_CASE: string;
  lowercase: string;
}

function App() {
  // 状态管理
  const [chineseInput, setChineseInput] = useState("");
  const [convertedNames, setConvertedNames] = useState<ConvertedName[]>([]);
  const [loading, setLoading] = useState(false);
  const [copiedIndex, setCopiedIndex] = useState(-1);
  const [copiedStyle, setCopiedStyle] = useState("");
  const [apiError, setApiError] = useState("");

  // 暗黑主题状态
  const [isDarkMode, setIsDarkMode] = useState(() => {
    const saved = localStorage.getItem("darkMode");
    return saved ? JSON.parse(saved) : false;
  });

  // 硅基流动 API 配置
  const SILICONFLOW_API_KEY = "你的api key";
  const SILICONFLOW_API_URL = "https://api.siliconflow.cn/v1/chat/completions";
  const MODEL_NAME = "Qwen/Qwen2.5-7B-Instruct";

  // 主题切换函数
  const toggleTheme = () => {
    const newTheme = !isDarkMode;
    setIsDarkMode(newTheme);
    localStorage.setItem("darkMode", JSON.stringify(newTheme));
  };

  // 命名转换函数
  const convertNamingStyles = (camelCaseName: string): ConvertedName => {
    // 将camelCase拆分为单词数组
    const words = camelCaseName
      .replace(/([A-Z])/g, " $1")
      .trim()
      .toLowerCase()
      .split(" ");

    return {
      original: camelCaseName,
      camelCase: camelCaseName,
      PascalCase: words
        .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
        .join(""),
      snake_case: words.join("_"),
      kebab_case: words.join("-"),
      UPPER_CASE: words.join("").toUpperCase(),
      UPPER_SNAKE_CASE: words.join("_").toUpperCase(),
      lowercase: words.join(""),
    };
  };

  // 处理中文输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setChineseInput(e.target.value);
    setApiError("");
  };

  // 复制变量名到剪贴板
  const copyToClipboard = (text: string, index: number, style: string) => {
    navigator.clipboard
      .writeText(text)
      .then(() => {
        setCopiedIndex(index);
        setCopiedStyle(style);
        message.success("已复制到剪贴板");
        setTimeout(() => {
          setCopiedIndex(-1);
          setCopiedStyle("");
        }, 2000);
      })
      .catch(() => {
        message.error("复制失败，请手动复制");
      });
  };

  // 调用硅基流动 API 生成英文变量名
  const generateVariableNames = async () => {
    if (!chineseInput.trim()) {
      message.warning("请输入中文描述");
      return;
    }

    setLoading(true);
    setApiError("");
    // setEnglishNames([]);
    setConvertedNames([]);

    try {
      const prompt = `请将以下中文转换为3种合适的小驼峰命名法（camelCase）英文变量名，遵循编程命名规范。 只返回变量名列表，每行一个，不要其他解释。 中文：${chineseInput}`;

      const response = await axios.post(
        SILICONFLOW_API_URL,
        {
          model: MODEL_NAME,
          messages: [
            {
              role: "system",
              content:
                "你是一个专业的编程命名助手，擅长将中文描述转换为规范的英文变量名，遵循各编程语言的命名约定。",
            },
            {
              role: "user",
              content: prompt,
            },
          ],
          temperature: 0.8,
          max_tokens: 500,
        },
        {
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${SILICONFLOW_API_KEY}`,
          },
        }
      );

      if (
        response.data &&
        response.data.choices &&
        response.data.choices.length > 0
      ) {
        const content = response.data.choices[0].message.content;
        const names = content
          .split("\n")
          .map((name: string) => {
            return name.replace(/^\d+\.\s*/, "").trim();
          })
          .filter((name: string) => name && name.length > 0);

        if (names.length > 0) {
          // setEnglishNames(names);
          // 转换为所有命名风格
          const converted = names.map((name: string) =>
            convertNamingStyles(name)
          );
          setConvertedNames(converted);
          message.success(`成功生成 ${names.length} 个变量名`);
        } else {
          setApiError("未能生成有效的变量名，请尝试其他描述");
        }
      } else {
        setApiError("API返回格式异常，请重试");
      }
    } catch (err) {
      console.error("API调用错误:", err);
      setApiError("调用API时发生错误，请检查API密钥或网络连接");
      message.error("生成失败，请稍后重试");
    } finally {
      setLoading(false);
    }
  };

  // 定义Button color的联合类型
  // type ButtonColor = "default" | "primary" | "success" | "warning" | "danger";

  // 获取命名风格标签
  const getNamingStyle = (style: string) => {
    const tagMap: {
      [key: string]: {
        color:
          | "default"
          | "blue"
          | "cyan"
          | "gold"
          | "green"
          | "lime"
          | "magenta"
          | "orange"
          | "pink"
          | "purple"
          | "red"
          | "yellow"
          | "primary"
          | "danger"
          | "volcano"
          | "geekblue";
        text: string;
      };
    } = {
      camelCase: { color: "blue", text: "小驼峰" },
      PascalCase: { color: "green", text: "大驼峰" },
      snake_case: { color: "orange", text: "蛇形命名" },
      kebab_case: { color: "purple", text: "连字符" },
      UPPER_CASE: { color: "red", text: "全大写" },
      UPPER_SNAKE_CASE: { color: "magenta", text: "大写蛇形" },
      lowercase: { color: "cyan", text: "全小写" },
    };

    return tagMap[style] || { color: "default", text: style };
  };

  // 命名风格说明数据
  const namingStyles: NamingStyle[] = [
    {
      type: "camelCase",
      desc: "驼峰命名法，首字母小写，后续单词首字母大写",
      example: "userName",
    },
    {
      type: "PascalCase",
      desc: "帕斯卡命名法，每个单词首字母都大写",
      example: "UserName",
    },
    {
      type: "snake_case",
      desc: "下划线命名法，单词全小写，用下划线连接",
      example: "user_name",
    },
    {
      type: "kebab-case",
      desc: "连字符命名法，单词全小写，用连字符连接",
      example: "user-name",
    },
    {
      type: "UPPERCASE",
      desc: "全大写命名法，所有字母大写",
      example: "USERNAME",
    },
    {
      type: "UPPER_SNAKE_CASE",
      desc: "大写下划线命名法，全大写用下划线连接",
      example: "USER_NAME",
    },
    {
      type: "lowercase",
      desc: "全小写命名法，所有字母小写",
      example: "username",
    },
  ];

  // 使用提示数据
  const usageTips = [
    "输入越具体，生成的变量名越精准",
    "可指定编程语言，如：'Java中的用户年龄'",
    "点击变量名后的复制按钮可快速复制",
    "自动生成7种常用命名风格",
    "生成结果基于Qwen2.5-7B-Instruct模型",
  ];

  return (
    <ConfigProvider
      theme={{
        algorithm: isDarkMode ? theme.darkAlgorithm : theme.defaultAlgorithm,
        token: {
          colorPrimary: "#1890ff",
        },
      }}
    >
      <Layout
        className="min-h-screen"
        style={{ backgroundColor: isDarkMode ? "#141414" : "#f5f5f5" }}
      >
        <Header
          style={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            backgroundColor: isDarkMode ? "#001529" : "#fff",
            borderBottom: `1px solid ${isDarkMode ? "#303030" : "#f0f0f0"}`,
            padding: "0 24px",
          }}
        >
          <Text
            strong
            style={{ color: isDarkMode ? "#fff" : "#000", fontSize: "18px" }}
          >
            中文变量名转英文工具
          </Text>
          <Space>
            <SunOutlined style={{ color: isDarkMode ? "#666" : "#1890ff" }} />
            <Switch
              checked={isDarkMode}
              onChange={toggleTheme}
              checkedChildren={<MoonOutlined />}
              unCheckedChildren={<SunOutlined />}
            />
            <MoonOutlined style={{ color: isDarkMode ? "#1890ff" : "#666" }} />
          </Space>
        </Header>

        <Content
          style={{
            maxWidth: 1200,
            margin: "0 auto",
            width: "100%",
          }}
        >
          <Card
            title="中文变量名转英文"
            style={{
              boxShadow: "0 4px 12px rgba(0, 0, 0, 0.05)",
              borderRadius: 8,
            }}
          >
            <Paragraph>
              输入中文描述，获取符合编程规范的英文变量名建议，自动生成7种命名风格。
            </Paragraph>

            <Search
              value={chineseInput}
              onChange={handleInputChange}
              placeholder="例如：用户姓名、订单金额、登录状态、商品列表..."
              enterButton="生成变量名"
              size="large"
              onSearch={generateVariableNames}
              loading={loading}
              style={{ marginBottom: 16 }}
            />

            {apiError && (
              <Alert
                message="错误提示"
                description={apiError}
                type="error"
                showIcon
                style={{ margin: "16px 0" }}
              />
            )}

            {convertedNames.length > 0 && (
              <>
                {convertedNames.map((nameObj, nameIndex) => (
                  <Card
                    key={nameIndex}
                    size="small"
                    style={{ marginBottom: 16 }}
                  >
                    <Row gutter={[8, 8]}>
                      {Object.entries(nameObj)
                        .filter(([key]) => key !== "original")
                        .map(([style, name]) => (
                          <Col
                            xs={24}
                            sm={12}
                            md={8}
                            lg={6}
                            key={`${nameIndex}-${style}`}
                          >
                            <div
                              style={{
                                display: "flex",
                                alignItems: "center",
                                justifyContent: "space-between",
                                padding: "8px 12px",
                                border: `1px solid ${
                                  isDarkMode ? "#303030" : "#f0f0f0"
                                }`,
                                borderRadius: "6px",
                                backgroundColor: isDarkMode
                                  ? "#1f1f1f"
                                  : "#fafafa",
                              }}
                            >
                              <div style={{ flex: 1, marginRight: 8 }}>
                                <Button
                                  color={getNamingStyle(style).color}
                                  variant="solid"
                                  onClick={() =>
                                    copyToClipboard(name, nameIndex, style)
                                  }
                                  icon={
                                    copiedIndex === nameIndex &&
                                    copiedStyle === style ? (
                                      <CheckOutlined />
                                    ) : null
                                  }
                                >
                                  {getNamingStyle(style).text}: {name}
                                </Button>
                              </div>
                            </div>
                          </Col>
                        ))}
                    </Row>
                  </Card>
                ))}
              </>
            )}
          </Card>

          <Row gutter={[16, 16]} style={{ marginTop: 24 }}>
            <Col xs={24} md={12}>
              <Card title="命名风格说明">
                <List
                  dataSource={namingStyles}
                  renderItem={(item) => (
                    <List.Item>
                      <List.Item.Meta
                        title={<Text code>{item.type}</Text>}
                        description={
                          <div>
                            <Text>{item.desc}</Text>
                            <br />
                            <Text type="secondary">示例: {item.example}</Text>
                          </div>
                        }
                      />
                    </List.Item>
                  )}
                />
              </Card>
            </Col>

            <Col xs={24} md={12}>
              <Card title="使用提示">
                <List
                  dataSource={usageTips}
                  renderItem={(item) => (
                    <List.Item>
                      <List.Item.Meta
                        avatar={<InfoOutlined style={{ color: "#1890ff" }} />}
                        description={item}
                      />
                    </List.Item>
                  )}
                />
              </Card>
            </Col>
          </Row>
        </Content>
      </Layout>
    </ConfigProvider>
  );
}

export default App;
